package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Category;
import com.example.exception.CustomException;
import com.example.mapper.CategoryMapper;
import com.example.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Override
    public void add(Category category) {
        Category item = getBaseMapper().selectOne(buildWrapper(category));
        if (!Objects.isNull(item)) {
            throw new CustomException(ResultCodeEnum.NAME_EXIST_ERROR);
        }
        getBaseMapper().insert(category);
    }

    @Override
    public void deleteById(Integer id) {
        getBaseMapper().deleteById(id);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        getBaseMapper().deleteBatchIds(ids);
    }

    @Override
    public Category selectById(Integer id) {
        return getBaseMapper().selectById(id);
    }

    @Override
    public List<Category> selectAll(Category category) {
        return getBaseMapper().selectList(buildWrapper(category));
    }

    @Override
    public Page<Category> selectPage(Category category, Integer pageNum, Integer pageSize) {
        Page<Category> page = new Page<>(pageNum, pageSize);
        return getBaseMapper().selectPage(page, buildWrapper(category));
    }

    public LambdaQueryWrapper<Category> buildWrapper(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!Objects.isNull(category.getName()), Category::getName, category.getName());
        return queryWrapper;
    }
}
